/**
 * 
 */
package com.ruoyi.core.service.impl;

import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.core.domain.Orders;
import com.ruoyi.core.domain.WxUserInfo;
import com.ruoyi.core.mapper.WxUserInfoMapper;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;

/**
 * @Author Lgc
 * @Date 2020年08月20日 下午10:20:04
 * 
 * @Description
 */
@Service
public class WeixinService {
	
	@Autowired
	private WxUserInfoMapper userInfoMapper;
	@Autowired
	private ServerConfig serverConfig;

	Logger log = LoggerFactory.getLogger(this.getClass());
	/**
	 * @Author Lgc
	 * @Date 2020年08月20日 下午10:20:04
	 *
	 * @Description 获取并更新微信用户信息
	 */

	public WxUserInfo getWxUserInfo(WxMpService wxMpService,WxMpUser wxMpUser, String userId) throws Exception {
		WxUserInfo u = userInfoMapper.selectWxUserInfoById(wxMpUser.getOpenId());
		if(null == u) {
			u = new WxUserInfo();
			BeanUtils.copyProperties(wxMpUser,u);
			u.setSex(wxMpUser.getSexId().longValue());
			u.setHeadimgurl(wxMpUser.getHeadImgUrl());

			u.setCreatedDate(new Date());
			u.setUserId(Long.valueOf(userId));
			userInfoMapper.insertWxUserInfo(u);
		} else {
			u.setLastUpdateDate(new Date());
			u.setUserId(Long.valueOf(userId));
			userInfoMapper.updateWxUserInfo(u);
		}
		return u;
	}
	
/*	public WxUserInfo queryByOpenId(String openid) {
		return userInfoMapper.selectWxUserInfoById(openid);
	}*/


	/**
	 * @param url
	 * @Author Lgc
	 * @Date 2020年08月24日 下午3:20:44
	 *
	 * @Description 获取扫一扫参数
	 */
	public WxJsapiSignature getScanParam(WxMpService wxMpService,String url) throws WxErrorException {
		return wxMpService.createJsapiSignature(url);
	}

	/**
	 * 发送模版消息
	 * @param wxMpService
	 * @param templateId
	 * @param orders
	 * @param openId
	 */
	public void sendMsg(WxMpService wxMpService, String templateId, Orders orders, String openId)  {
		WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
				.toUser(openId)
				.templateId(templateId)
				.url("")
				.build();
		if (StringUtils.isEmpty(orders.getExpressNumber())){
			throw  new BusinessException("运单号不能为空");
		}
		templateMessage.addWxMpTemplateData(new WxMpTemplateData("first","您好，您申请的礼品已经发货","#173177"));
		templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword1",orders.getOrderAddress(),"#173177"));
		templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword2", orders.getConsignee(),"#173177"));
		templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword3",orders.getTel(),"#173177"));
		templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword4",orders.getExpressNumber(),"#173177"));
		templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword5",orders.getLogisticsName(),"#173177"));
		templateMessage.addWxMpTemplateData(new WxMpTemplateData("remark","谢谢提货","#173177"));

		String msgId = null;
		try {
			msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		if (StringUtils.isEmpty(msgId)){
//			throw new BusinessException("该用户尚未关注公众号");
			log.info("该用户尚未关注公众号");
		}
	}


	/**
	 * @param url 
	 * @Author lgc
	 * @Date 2020年08月20日 下午3:20:44
	 *
	 * @Description 获取扫一扫参数
	 *//*
	public ScanParameter getScanParam(String url) throws Exception {
		String appId = systemParameterService.getValue("WEIXIN_APPID");
		String appsecret = systemParameterService.getValue("WEIXIN_SECRET");
		AccessToken at = getAccessToken(appId, appsecret);
		JsapiTicket jt = getJsapiTicket(at.getAccess_token());
		String nonceStr = UUID.randomUUID().toString();
		String timestamp = Long.toString(System.currentTimeMillis() / 1000);
		String signature = getSignature(jt.getTicket(), nonceStr, timestamp, url);

		ScanParameter sp = new ScanParameter();
		sp.setAppId(appId);
		sp.setNonceStr(nonceStr);
		sp.setTimestamp(timestamp);
		sp.setSignature(signature);
		
		log.info("ScanParameter:" + sp);
		
		return sp;
	}

	*//**
	 * @Author lgc
	 * @Date 2017年11月30日 下午3:36:46
	 *
	 * @Description 获取AccessToken
	 *//*
	public AccessToken getAccessToken(String appId, String appsecret) throws Exception {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret="
				+ appsecret;
		String result = HttpUtil.doGet(url);
		com.alibaba.fastjson.JSONObject jo = com.alibaba.fastjson.JSONObject.parseObject(result);
		AccessToken at = new AccessToken();
		at.setAccess_token(jo.getString("access_token"));
		at.setExpires_in(jo.getInteger("expires_in"));
		return at;
	}

	*//**
	 * @Author lgc
	 * @Date 2017年11月30日 下午4:08:58
	 *
	 * @Description 获取JsapiTicket
	 *//*
	public JsapiTicket getJsapiTicket(String access_token) throws Exception {
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
		String result = HttpUtil.doGet(url);
		com.alibaba.fastjson.JSONObject jo = com.alibaba.fastjson.JSONObject.parseObject(result);
		JsapiTicket jt = new JsapiTicket();
		jt.setErrcode(jo.getInteger("errcode"));
		jt.setErrmsg(jo.getString("errmsg"));
		jt.setExpires_in(jo.getInteger("expires_in"));
		jt.setTicket(jo.getString("ticket"));
		return jt;
	}

	*//**
	 * @Author lgc
	 * @Date 2017年11月30日 下午4:27:34
	 *
	 * @Description 获取签名
	 *//*
	public String getSignature(String jsapi_ticket, String nonceStr, String timestamp, String url) throws NoSuchAlgorithmException {
		String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
		String signature = EncodeUtil.encodeBySHA1(str);
		return signature;
	}*/

}
